package me.itsoo.elasticbatis.executor;

import me.itsoo.elasticbatis.mapping.BoundSql;
import me.itsoo.elasticbatis.mapping.MappedStatement;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * Executor
 *
 * @author zhangxy4
 * @version 0.0.1
 * @since 2025/4/9
 */
public class Executor {
    private static final String ES_METHOD = "POST";
    private static final String ES_ENDPOINT = "/_opendistro/_sql";

    public int update(MappedStatement ms, Object parameter) throws IOException {
        // TODO
        return -1;
    }

    public <E> List<E> query(MappedStatement ms, Object parameter, BoundSql boundSql) throws IOException {
        Request req = new Request(ES_METHOD, ES_ENDPOINT);
        req.setJsonEntity(this.getQueryDsl(boundSql.getSql()));
        Response resp = ms.getConfiguration()
                .getEnvironment()
                .getDataSource()
                .getLowLevelClient()
                .performRequest(req);
        String json = EntityUtils.toString(resp.getEntity());
        //!FIXME 转换查询结果
        return (List<E>) Arrays.asList(json);
    }

    public <E> List<E> query(MappedStatement ms, Object parameter) throws IOException {
        // TODO
        return this.query(ms, parameter, ms.getBoundSql());
    }

    public void close() {
        // TODO
    }

    public boolean isClosed() {
        // TODO
        return false;
    }

    private String getQueryDsl(String sql) {
        return String.format("{\"query\":\"%s\"}", sql);
    }
}
